const command = (type) => {
    try {
        return document.execCommand(type);
    } catch (err) {
        return false;
    }
}

let Toast = {
    show: () => {}
}

const copy = {
    init: (obj) => {
        Toast = obj
    },
    mounted(el, binding) {
        let _this = this;
        el.handler = () => {
            el.$value = (typeof binding.value == 'undefined' ? el.innerText : binding.value)
            if (!el.$value) {
                Toast.error('无复制内容')
                return
            }
            const textarea = document.createElement('textarea')
            textarea.readOnly = 'readonly'
            textarea.style.position = 'absolute'
            textarea.style.left = '-9999px'
            textarea.value = el.$value
            document.body.appendChild(textarea)
            textarea.select()
            const result = command('Copy')
            if (result) {
                Toast.success('复制成功')
            } else {
                Toast.error('复制失败');
            }
            document.body.removeChild(textarea)
        }
        el.addEventListener('click', el.handler)
    },
    beforeUnmount(el) {
        el.removeEventListener('click', el.handler)
    }
}

export default copy